/*
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.spice.servlet.inject.strategy;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.spice.servlet.core.components.ComponentFactory;
import org.spice.servlet.core.components.Resource;
import org.spice.servlet.dispatcher.handler.ClassPathScanner;
import org.spice.servlet.dispatcher.handler.SpiceSingleton;

public class ResourcesLocator implements Resource{

	private 
	String locations;

	protected 
	static final ClassPathScanner SCANNER = new ClassPathScanner();

	public 
	ResourcesLocator(String locations) {
		this.locations = locations;
	}

	@Override
	public 
	List<ComponentFactory> getResources() {
		final List<ComponentFactory> factory  = new ArrayList<ComponentFactory>();
		try {
			final List<Class<?>>clazzes = getClasses();
			for(final Class<?> singleClass : clazzes){
				factory.add(new ComponentImplication(singleClass));
			}
		} catch (IOException e) {
			return new ArrayList<ComponentFactory>();
		} catch (ClassNotFoundException e) {
			return new ArrayList<ComponentFactory>();
		}
		return factory;
	}

	/**
	 * 
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	protected 
	List<Class<?>> getClasses() throws IOException, ClassNotFoundException {
		final SpiceSingleton bean = SpiceSingleton.getInstance();
		final List<Class<?>> clazzes = new ArrayList<Class<?>>();
		final List<String> resources = SCANNER.readResources(locations);
		for(final String resource : resources){
			clazzes.add(Class.forName(resource));
		}
		bean.setListOfClasses(clazzes);
		return clazzes;
	}

	@Override
	public 
	Map<String, String> getInterfaceNames() {
		final Map<String, String> interfaceMapping = new HashMap<String, String>();
		for(ComponentFactory components : getResources()){
			final Class<?>[] clazzes = components.getComponentClass().getInterfaces();
			for(final Class<?> clazz : clazzes){
				interfaceMapping.put(clazz.getName(), components.getComponentClass().getName());
			}
		}
		return interfaceMapping;
	}

	

}
